package com.hugesoft.jxgs.activity;

import java.util.Date;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.hugesoft.jxgs.R;
import com.hugesoft.jxgs.activity.base.BaseActivity;
import com.hugesoft.jxgs.utils.CheckInputUtil;
import com.hugesoft.logic.managers.LogicManager;
import com.hugesoft.logic.managers.common.Constans;
import com.hugesoft.logic.module.Bus;
import com.hugesoft.logic.module.DriverLicence;
import com.hugesoft.logic.module.Police;
import com.hugesoft.utils.Util;

public class BusActivity extends BaseActivity implements OnClickListener {
	Button  mSearchDriverInfo, mSearchPoliceInfo, mTakePic,
			mBtnSubmit,mBtnSignature;
	TextView tvPlateNumber,tvDriverType, tvDriverName, tvDriverAge, tvPoliceName, tvPoliceNo;
	EditText etStart, etEnd, etDriverLicenceNo, etDriverTime,etTel,
			etPermittedPassengerNo, etRealPassengerNo,etComment;
	RadioButton rbtnYearChecked, rbtnNoYearChecked;
	RadioButton rbtnSafeDeviceReady, rbtnNoSafeDeviceReady;
	RadioButton rbtnWheelBroken, rbtnNoWheelBroken;
	RadioButton rbtnTaught, rbtnNoTaught;

	public static int REQUESTCODE_ADDLICENCE = 1000;
	public static int REQUESTCODE_SEARCHPOLICE = REQUESTCODE_ADDLICENCE + 1;
	public static int REQUESTCODE_CAPTURE = REQUESTCODE_SEARCHPOLICE + 1;
	public static int REQUESTCODE_SIGNATURE = REQUESTCODE_CAPTURE + 1;
	
	private Bus mBusInfo = new Bus();
	private static String TAG = "BusActivity";
	
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			dismissDialog();
			switch (msg.what) {
			case Constans.ADD_BUS_SUCCESS:
				// 登录成功，摘取该用户的信息
				Toast.makeText(BusActivity.this, "上传成功", Toast.LENGTH_LONG).show();
				Intent intent = new Intent();
				intent.putExtra(Constans.TAGPLATENUMBER, mBusInfo.getPlatenumber());
				setResult(0,intent);
				finish();
				break;
			case Constans.ADD_BUS_FAILED:
				Toast.makeText(BusActivity.this,
						msg.obj == null ? "上传失败" : msg.obj.toString(),
						Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		Long busid = getIntent().getLongExtra(Constans.TAGBUSID, 0);
		Bus tmpbusInfo = LogicManager.busManager().loadbusinfo(busid);
		initUI();
		if (tmpbusInfo == null) {
			String platenumber = getIntent().getStringExtra(Constans.TAGPLATENUMBER);
			if (platenumber != null) {
				tvPlateNumber.setText("车牌号码:"+platenumber);
			}
			mBusInfo.setPlatenumber(platenumber);
			mBusInfo.setPoliceid(LogicManager.policeManager().getcurrentpolice().getId());
		}
		else {
			mBusInfo.setPlatenumber(tmpbusInfo.getPlatenumber());
			mBusInfo.setStartposition(tmpbusInfo.getStartposition());
			mBusInfo.setEndposition(tmpbusInfo.getEndposition());
			mBusInfo.setDriverid(tmpbusInfo.getDriverid());
			mBusInfo.setDrivertime(tmpbusInfo.getDrivertime());
			mBusInfo.setTelnum(tmpbusInfo.getTelnum());
			mBusInfo.setPermittedpassengernum(tmpbusInfo.getPermittedpassengernum());
			mBusInfo.setActualpassengernum(tmpbusInfo.getActualpassengernum());
			mBusInfo.setIsyearchecked(tmpbusInfo.getIsyearchecked());
			mBusInfo.setIssafedeviceready(tmpbusInfo.getIssafedeviceready());
			mBusInfo.setIswheelbroken(tmpbusInfo.getIswheelbroken());
			mBusInfo.setIstaught(tmpbusInfo.getIstaught());
			mBusInfo.setPoliceid(tmpbusInfo.getPoliceid());
			mBusInfo.setComment(tmpbusInfo.getComment());
			//以下三项需要更新的，就不复制了
//			mBusInfo.setPic(tmpbusInfo.getPic());
//			mBusInfo.setCheckdate(tmpbusInfo.getCheckdate());
			setUIWithBusInfo();
		}
	}

	private void initUI() {
		setContentView(R.layout.activitybus);
		((TextView) findViewById(R.id.titleTextView)).setText("客运车辆");
		findViewById(R.id.backImg).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				finish();
			}
		});


		tvPlateNumber = (TextView) findViewById(R.id.tvPlateNumber);
		mSearchDriverInfo = (Button) findViewById(R.id.btnSearchDriverLicence);
		mSearchDriverInfo.setOnClickListener(this);
		mSearchPoliceInfo = (Button) findViewById(R.id.btnSearchPolice);
		mSearchPoliceInfo.setOnClickListener(this);
		mTakePic = (Button) findViewById(R.id.btnTakePic);
		mTakePic.setOnClickListener(this);
		mBtnSignature = (Button) findViewById(R.id.btnSignature);
		mBtnSignature.setOnClickListener(this);
		mBtnSubmit = (Button) findViewById(R.id.btnsubmit);
		mBtnSubmit.setOnClickListener(this);
		
		
		etDriverLicenceNo = (EditText) findViewById(R.id.etDriverNo);

		tvPoliceName = (TextView) findViewById(R.id.tvPoliceName);
		tvPoliceName.setText("民警姓名："
				+ LogicManager.policeManager().getcurrentpolice().getName());
		tvPoliceNo = (TextView) findViewById(R.id.tvPoliceNo);
		tvPoliceNo
				.setText("民警警号："
						+ LogicManager.policeManager().getcurrentpolice()
								.getPoliceno());
		tvDriverName = (TextView) findViewById(R.id.tvDriverName);
		tvDriverType = (TextView) findViewById(R.id.tvDriverType);
		tvDriverAge = (TextView) findViewById(R.id.tvDriverAge);

		rbtnSafeDeviceReady = (RadioButton) findViewById(R.id.rbtnsafedeviceready);
		rbtnNoSafeDeviceReady = (RadioButton) findViewById(R.id.rbtnnosafedeviceready);
		rbtnTaught = (RadioButton) findViewById(R.id.rbtntaugnt);
		rbtnNoTaught = (RadioButton) findViewById(R.id.rbtnnotaught);
		rbtnWheelBroken = (RadioButton) findViewById(R.id.rbtnwheelbroken);
		rbtnNoWheelBroken = (RadioButton) findViewById(R.id.rbtnnowheelbroken);
		rbtnYearChecked = (RadioButton) findViewById(R.id.rbtnyearchecked);
		rbtnNoYearChecked = (RadioButton) findViewById(R.id.rbtnnoyearchecked);
		
		etStart = (EditText) findViewById(R.id.etStart);
		etEnd = (EditText) findViewById(R.id.etEnd);

		etDriverTime = (EditText) findViewById(R.id.etDriverTime);
		etTel = (EditText) findViewById(R.id.etTel);
		etPermittedPassengerNo = (EditText) findViewById(R.id.etPermittedPassengerNo);
		etRealPassengerNo = (EditText) findViewById(R.id.etRealParsengerNo);
		etComment = (EditText)findViewById(R.id.etComment);
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
//		case R.id.btnSearchBusInfo:
//			String platenumber = etBusNo.getText().toString();
//			if (CheckInputUtil.isbusnoverified(platenumber)) {
//				List<Bus> buslist = LogicManager.busManager().loadbusinfo(
//						platenumber);
//				if (buslist != null && buslist.size() != 0) {
//					Intent intent = new Intent(BusActivity.this,
//							ListActivityBusInfo.class);
//					intent.putExtra(ListActivityBusInfo.TAGBUSID, platenumber);
//					startActivityForResult(intent, REQUESTCODE_BUSHISTORY);
//				} else {
//					Util.showToast(BusActivity.this, "没有该车号的数据");
//				}
//			} else {
//				Util.showToast(BusActivity.this, "车号非法");
//			}
//			break;
		case R.id.btnSearchDriverLicence:
			String licenceno = etDriverLicenceNo.getText().toString();
			if (CheckInputUtil.islicencenoverified(licenceno)) {
				DriverLicence licence = LogicManager.driverLicenceManager()
						.loadlicenceinfo(licenceno);
				if (licence != null) {
					setDriverUIWithLicence(licence);
					mBusInfo.setDriverid(licence.getId());
				} else {
					Util.showToast(BusActivity.this, "没有该驾照数据，请创建");
					Intent intent = new Intent(BusActivity.this,
							AddLicenceActivity.class);
					intent.putExtra(AddLicenceActivity.TAGLICENCENO, licenceno);
					startActivityForResult(intent, REQUESTCODE_ADDLICENCE);
				}
			} else {
				Util.showToast(BusActivity.this, "驾照非法");
			}
			break;
		case R.id.btnSearchPolice:
			Intent i = new Intent(BusActivity.this,
					ListActivityPoliceInfo.class);
			startActivityForResult(i, REQUESTCODE_SEARCHPOLICE);

			break;
		case R.id.btnTakePic:
			startActivityForResult(new Intent(BusActivity.this,
					CaptureActivity.class).putExtra(CaptureActivity.TAGIMGPATH,
					mBusInfo.getPic()), REQUESTCODE_CAPTURE);
			break;
		case R.id.btnsubmit:
			submitbus();
			break;
		case R.id.btnSignature:
			startActivityForResult(new Intent(BusActivity.this,SignatureActivity.class),REQUESTCODE_SIGNATURE);			
		default:
			break;
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUESTCODE_ADDLICENCE
				&& resultCode == AddLicenceActivity.RSTADDLICENCE) {
			// 添加驾照成功
			String licenceno = data
					.getStringExtra(AddLicenceActivity.TAGLICENCENO);
			DriverLicence licence = LogicManager.driverLicenceManager()
					.loadlicenceinfo(licenceno);

			setDriverUIWithLicence(licence);

			mBusInfo.setDriverid(licence.getId());

		} else if (requestCode == REQUESTCODE_SEARCHPOLICE
				&& resultCode == ListActivityPoliceInfo.RSTSEARCHPOLICE) {
			String policeno = data
					.getStringExtra(ListActivityPoliceInfo.TAGPOLICENO);
			Police police = LogicManager.policeManager().loadpolice(
					policeno);
			tvPoliceName.setText("民警姓名：" + police.getName());
			tvPoliceNo.setText("民警警号：" + police.getPoliceno());

			mBusInfo.setPoliceid(police.getId());
		} else if (requestCode == REQUESTCODE_CAPTURE) {
			String picPath = data.getStringExtra(CaptureActivity.TAGIMGPATH);
			mBusInfo.setPic(picPath);
		}else if (requestCode == REQUESTCODE_SIGNATURE) {
			String sigPicPath = data.getStringExtra(SignatureActivity.TAGSIGIMGPATH);
			mBusInfo.setSig(sigPicPath);
		}
//		else if (requestCode == REQUESTCODE_BUSHISTORY && resultCode == ListActivityBusInfo.RSTBUSHISTORY) {
//			Long busId = data.getLongExtra(ListActivityBusInfo.TAGBUSID, 0);
//			mBusInfo = LogicManager.busManager().loadbusinfo(busId);
//			setUIWithBusInfo();
//		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void submitbus() {
		mBusInfo.setStartposition(etStart.getText().toString());
		mBusInfo.setEndposition(etEnd.getText().toString());
		mBusInfo.setDrivertime(etDriverTime.getText().toString());
		mBusInfo.setTelnum(etTel.getText().toString());
		mBusInfo.setPermittedpassengernum(etPermittedPassengerNo.getText().length() == 0?null:Integer
				.parseInt(etPermittedPassengerNo.getText().toString()));
		mBusInfo.setActualpassengernum(etRealPassengerNo.getText().length() == 0?null:Integer.parseInt(etRealPassengerNo
				.getText().toString()));
		mBusInfo.setCheckdate(new Date());
		mBusInfo.setIstaught(rbtnTaught.isChecked());
		mBusInfo.setIsyearchecked(rbtnYearChecked.isChecked());
		mBusInfo.setIssafedeviceready(rbtnSafeDeviceReady.isChecked());
		mBusInfo.setIswheelbroken(rbtnWheelBroken.isChecked());
		mBusInfo.setComment(etComment.getText().toString());
		if (checkbus()) {
			LogicManager.busManager().addbusinfo(mBusInfo, mHandler);
		}
	}

	private boolean checkbus() {
		boolean ret = true;
		
		if (mBusInfo.getDriverid() == null) {
			Util.showToast(BusActivity.this, "驾照信息错了哦，亲");
			ret = false;
			return ret;
		}
		if (!CheckInputUtil.isbusnoverified(mBusInfo.getPlatenumber())) {
			Util.showToast(BusActivity.this, "车牌号码号码错了哦，亲");
			ret = false;
			return ret;
		}
		if (mBusInfo.getPoliceid() == null) {
			Util.showToast(BusActivity.this, "警察信息错了哦，亲");
			ret = false;
			return ret;
		}
		
		if (mBusInfo.getDrivertime() == null || mBusInfo.getDrivertime().length() == 0) {
			Util.showToast(BusActivity.this, "驾驶时间错了哦，亲");
			ret = false;
			return ret;
		}
		
		if (mBusInfo.getTelnum() == null || mBusInfo.getTelnum().length() != 11) {
			Util.showToast(BusActivity.this, "电话号码号码错了哦，亲");
			ret = false;
			return ret;
		}
		
		if (mBusInfo.getActualpassengernum() == null) {
			Util.showToast(BusActivity.this, "实载信息错了哦，亲");
			ret = false;
			return ret;
		}
		
		if (mBusInfo.getPermittedpassengernum() == null) {
			Util.showToast(BusActivity.this, "核载信息错了哦，亲");
			ret = false;
			return ret;
		}
		
		if (!CheckInputUtil.isbuspicverified(mBusInfo.getPic())) {
			Util.showToast(BusActivity.this, "至少拍两张照片哦，亲");
			ret = false;
			return ret;
		}
		
		if (!CheckInputUtil.issigverified(mBusInfo.getSig())) {
			Util.showToast(BusActivity.this, "需要签名哦，亲");
			ret = false;
			return ret;
		}
		
		//实载人数大于核载人数
		if (mBusInfo.getActualpassengernum() > mBusInfo.getPermittedpassengernum()) {
			Util.showToast(BusActivity.this, "超载了哦，亲");
			ret = false;
			return ret;
		}
		return ret;
	}
	
	private void setUIWithBusInfo()
	{
		mBusInfo.setPoliceid(LogicManager.policeManager().getcurrentpolice().getId());
		tvPlateNumber.setText("车辆号牌:"+mBusInfo.getPlatenumber());
		etStart.setText(mBusInfo.getStartposition());
		etEnd.setText(mBusInfo.getEndposition());
		
		DriverLicence licence = LogicManager.driverLicenceManager().loadlicenceinfo(mBusInfo.getDriverid());
		setDriverUIWithLicence(licence);
		
		etTel.setText(mBusInfo.getTelnum());
		etDriverTime.setText(mBusInfo.getDrivertime().toString());
		etPermittedPassengerNo.setText(mBusInfo.getPermittedpassengernum().toString());
//		etRealPassengerNo.setText(mBusInfo.getActualpassengernum().toString());
		etComment.setText(mBusInfo.getComment());
		
		rbtnSafeDeviceReady.setChecked(mBusInfo.getIssafedeviceready());
		rbtnNoSafeDeviceReady.setChecked(!mBusInfo.getIssafedeviceready());
		
		rbtnTaught.setChecked(mBusInfo.getIstaught());
		rbtnNoTaught.setChecked(!mBusInfo.getIstaught());
		
		rbtnWheelBroken.setChecked(mBusInfo.getIswheelbroken());
		rbtnNoWheelBroken.setChecked(!mBusInfo.getIswheelbroken());
		
		rbtnYearChecked.setChecked(mBusInfo.getIsyearchecked());
		rbtnNoYearChecked.setChecked(!mBusInfo.getIsyearchecked());
		
	}
	
	private void setDriverUIWithLicence(DriverLicence licence)
	{
		etDriverLicenceNo.setText(licence.getLicenceno());
		tvDriverType.setText("驾照类型:"+licence.getType());
		tvDriverAge.setText("驾龄:"+licence.getDriverage().toString());
		tvDriverName.setText("司机姓名:"+licence.getDrivername());
	}
}
